package com.huifeng.dao.impl;

import com.huifeng.bean.Car;
import com.huifeng.dao.CarDao;
import com.huifeng.utils.PageUtils;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;
import java.util.List;

public class CarDaoimpl implements CarDao {
    //首先加载资源
    QueryRunner runner =new QueryRunner(new ComboPooledDataSource());
    @Override
    public int insertCar(Car car) {

        String sql="INSERT INTO car(brand,color,price)VALUES(?,?,?)";
        int row =0;
        try {
            row=  runner.update(sql,car.getBrand(),car.getColor(),car.getPrice() );
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return row;}

    @Override
    public int findtotalcount() {
        String sql="select count(*) from car";
        int count =0;
        try {
            Object obj = runner.query(sql, new ScalarHandler<>());
            count=Integer.parseInt(obj.toString());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return count;
    }

    @Override
    public List<Car> selectByPage(PageUtils pu) {
        String sql="select*from car limit ?,?";
        List<Car> list =null;
        try {
            list = runner.query(sql, new BeanListHandler<>(Car.class),
                    pu.getStartIndex(), pu.getPageSize());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }
}
